package com.rk.pethome.user.Service.Impl;
import com.alibaba.fastjson.JSONObject;
import com.rk.pethome.basic.util.AjaxResult;
import com.rk.pethome.basic.util.MD5Utils;
import com.rk.pethome.basic.util.RedisUtils;
import com.rk.pethome.user.Service.IWechatService;
import com.rk.pethome.user.constant.WechatConstant;
import com.rk.pethome.user.domain.User;
import com.rk.pethome.user.domain.WechatUser;
import com.rk.pethome.user.mapper.UserMapper;
import com.rk.pethome.user.mapper.WechatUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rk.pethome.basic.util.HttpClientUtils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class IWechatServiceImpl implements IWechatService {

    @Autowired
    private WechatUserMapper wechatUserMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 跳转到绑定界面，或者直接的登录
     * 通过code获取token
     * @param code  授权码
     * @return
     */
    @Override
    public Map<String, Object> gotoBinderOrLogin(String code) throws UnsupportedEncodingException {
        System.out.println("获取的code:"+code);
        //获取token的url地址
        String tokenUrl = WechatConstant.TOKENURL
                .replace("APPID", WechatConstant.APPID)
                .replace("SECRET",WechatConstant.SECRET)
                .replace("CODE",code);
        //使用HttpClientUtils工具类发送请求,返回Json字符串
        String tokenJsonStr = HttpClientUtils.httpGet(tokenUrl);
        //把Json字符串转换为json对象
        JSONObject jsonObject= JSONObject.parseObject(tokenJsonStr);
        //获取token
        String access_token = jsonObject.getString("access_token");
        System.out.println("access_token:  "+access_token);
        //获取openid
        String openid = jsonObject.getString("openid");

        //通过oppenid查询微信用户
        WechatUser wechatUser = wechatUserMapper.loadByOpenid(openid);
        System.out.println("wechatUser:v  "+wechatUser);
        //创建一个map，该map要返回到前端去(前端根据返回的结果值，就可以判定我是否跳转到绑定界面)
        Map<String,Object> map=new HashMap<>();

        //如果微信用户为空,就通过token获取资源信息村入t_wxuser
        if(wechatUser==null){
            //获取用户信息的Url地址
            String userinfourl = WechatConstant.USERINFOURL
                    .replace("ACCESS_TOKEN", access_token)
                    .replace("OPENID", openid);
            //通过HttpClientUtils工具类发送请求获取用户信息,json字符串
            String userinfoJsonStrl = HttpClientUtils.httpGet(userinfourl);
            //解决乱码问题
            String userinfoJsonStr = new String(userinfoJsonStrl.getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("微信用户信息"+userinfoJsonStr);
            //将json字符串转换为json对象
            JSONObject userinfojson = JSONObject.parseObject(userinfoJsonStr);
            //获取用户信息，将用户信息添加到t_wxuser表中
            WechatUser wxuser=new WechatUser();
            //设置地址      2021年10月以后微信开放平台将不再提供用户的性别和地址
            /*wxuser.setAddress(userinfojson.getString("country")
                    +userinfojson.getString("province")
                    +userinfojson.getString("city"));*/
            //设置性别
            //wxuser.setSex(userinfojson.getIntValue("sex"));

            //设置头像
            wxuser.setHeadimgurl(userinfojson.getString("headimgurl"));
            //设置昵称
            wxuser.setNickname(userinfojson.getString("nickname"));
            //设置openid
            wxuser.setOpenid(openid);

            //保存wxuser对象
            wechatUserMapper.saveUser(wxuser);

            //如果map保存了openid,就意味着要跳转到绑定界面
            //绑定界面输入用户名和密码查出来user  通过openid查出来wxuser然后进行绑定
            map.put("openid",openid);
            return map;

        }


        //获取绑定的user对象
        User user = wechatUser.getUser();

        //如果user为空，就跳转到绑定界面  就是该用户未绑定
        if(user==null){
            //跳转到绑定界面
            map.put("openid",openid);
            return map;
        }

        //该用户已绑定，直接进行登录操作

         //redis的key值
        String token = UUID.randomUUID().toString();
        //将loginuser转化为json字符串 存入redis
        RedisUtils.INSTANCE.set(token,JSONObject.toJSONString(user),30*60);

        //将redis中存储的token保存到map中返回到前端页面
        map.put("token",token);
        System.out.println("微信登录的token值:"+token);
        map.put("loginUser",user);

        //user不为空，说明该微信用户已经存储到t_wxuser表中，并且已进行绑定，可以直接登录
        return map;
    }

    /**
     * 绑定用户
     *
     * @param param
     * @return
     */
    @Override
    public AjaxResult binder(HashMap<String, String> param) {
        String username = param.get("username");
        //通过用户名查询到用户
        User user = userMapper.loadByUsername(username);
        //校验用户
        if(user==null)
            return new AjaxResult(false,"用户名错误!!");
        if(user.getState()==0)
            return new AjaxResult(false,"该用户未激活，请先激活!");
        String password = param.get("password");
        if((MD5Utils.encrypByMd5(password)+user.getSalt()).equals(user.getPassword()))
            return new AjaxResult(false,"密码错误!!");

        //进行绑定
        String openid = param.get("openid");
        wechatUserMapper.updateByOpenid(user,openid);

        //redis的key值
        String token = UUID.randomUUID().toString();
        //将loginuser转化为json字符串 存入redis
        RedisUtils.INSTANCE.set(token,JSONObject.toJSONString(user),30*60);

        //将redis中存储的token保存到map中返回到前端页面
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        System.out.println("微信登录的token值:"+token);
        map.put("loginUser",user);
        return new AjaxResult().setResult(map);
    }
}
